<?php

namespace addons\xilujob;

use app\common\library\Menu;
use app\common\model\xilujob\Chat;
use app\common\model\xilujob\Config;
use app\common\model\xilujob\JobInterview;
use app\common\model\xilujob\MoneyLog;
use think\Addons;
use think\db\Expression;
use think\Exception;
use think\Request;

use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\JobApply;
use app\common\model\xilujob\PersonalMessage as PersonalMessageModel;
use app\common\model\xilujob\Resume;
use app\common\model\xilujob\ResumeViewLog;
use app\common\model\xilujob\XilujobUser;
use think\Db;
use think\Log;

/**
 * 插件
 */
class Xilujob extends Addons
{

    /**
     * 插件安装方法
     * @return bool
     */
    public function install()
    {

        $menu = include ADDON_PATH . 'xilujob' . DS . 'data' . DS . 'menu.php';
	    Menu::create($menu);
        return true;
    }

    /**
     * 插件卸载方法
     * @return bool
     */
    public function uninstall()
    {
        Menu::delete("xilujob");
        return true;
    }

    /**
     * 插件启用方法
     * @return bool
     */
    public function enable()
    {
        Menu::enable("xilujob");
        return true;
    }

    /**
     * 插件禁用方法
     * @return bool
     */
    public function disable()
    {
        Menu::disable("xilujob");
        return true;
    }

    /**
     * 插件升级方法
     * @return bool
     */
    public function upgrade()
    {
        $menu = include ADDON_PATH . 'xilujob' . DS . 'data' . DS . 'menu.php';
        //如果菜单有变更则升级菜单
        Menu::upgrade('xilujob', $menu);
        return true;
    }

    /**
     * 应用初始化
     */
    public function appInit()
    {
        // 公共方法
        require_once __DIR__ . '/helper.php';
        //先判断是否已经通过其它方式引入了此类
        if(!class_exists("\PHPQRCode\QRcode")){
            \think\Loader::addNamespace('PHPQRCode', ADDON_PATH . 'xilujob' . DS . 'library' . DS . 'PHPQRCode' . DS.'lib'.DS.'PHPQRCode'.DS);
        }

        // database 增加断线重连参数
        $database = \think\Config::get('database');
        $database['break_reconnect'] = true;        // 断线重连
        \think\Config::set('database', $database);

        \think\Console::addDefaultCommands([
            'addons\\xilujob\\chatprograms\\GatewayWorker\\start',
        ]);
    }

    /**
     * 简历被查看， 给个人用户发消息
     */
    public function xilujobResumeViewed(ResumeViewLog &$resumeViewLog) {
        $enterpriseInfo = EnterpriseInfo::field('id,user_id,company_id,full_name,company_name')->where(['company_id'=>$resumeViewLog->company_id])->find();
        $company = XilujobUser::field('id,user_id,enterprise_group_id,trainer_group_id')->where(['user_id'=>$enterpriseInfo->user_id])->find();
        $resume = Resume::field('id,user_id')->find($resumeViewLog->resume_id);
        if(!$enterpriseInfo || !$resume) {
            //看简历的非企业
            return;
        }
        $model = PersonalMessageModel::create([
            'user_id' => $resume->user_id,
            'user_group_id' => XilujobUser::GROUP_MEMBER,
            'type' => PersonalMessageModel::TYPE_RESUME_VIEWED,
            'title' => '有企业查看你的简历哦！',
            'content' => sprintf('%s查看了你的简历，耐心等待对方好消息吧~',$enterpriseInfo->company_name),
            'extra' => ['company_id'=>$resumeViewLog->company_id,'company_group_id'=>$company->enterprise_group_id?:$company->trainer_group_id]
        ]);
        XilujobUser::where('user_id', $resume->user_id)->update(['personal_message'=>Db::raw('personal_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        //Notification::instance()->sendResumeViewed($resumeViewLog); // 后来有接入其它通知再打开
    }

    /**
     * 投递简历，提醒企业用户
     */
    public function xilujobApplySent(JobApply &$apply) {
        // 发消息
        $job = Job::field('id,user_id,job_name')->where('id',$apply->job_id)->find();
        $model = PersonalMessageModel::create([
            'user_id' => $job->user_id,
            'company_id' => $apply->company_id,
            'user_group_id' => XilujobUser::GROUP_COMPANY,
            'type' => PersonalMessageModel::TYPE_APPLY_SENT,
            'title' => '新的简历投递',
            'content' => "您的\"{$job->job_name}\"岗位有新的投递，请及时处理。",
            'extra' => ['user_id'=>$apply->user_id,'resume_id'=>$apply->resume_id]
        ]);
        XilujobUser::where('user_id', $job->user_id)->update(['discover_message'=>Db::raw('discover_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        try{
            Chat::add_chat([
                'message'=> ['type'=> "apply", 'content'=> ['text'=> "投递成功",'apply_id'=>$apply->id]],
                'puser_id'=> $job['user_id'],
                'type'=> "chat"
            ]);
        }catch (\Exception $e){

        }

        //Notification::instance()->sendApplySent($apply);
    }

    /**
     * 投递被拒绝， 通知投递用户
     */
    public function xilujobApplyRejected(JobApply &$apply) {
        // 发消息
        $job = Job::field('id,job_name')->where('id',$apply->job_id)->find();
        $model = PersonalMessageModel::create([
            'user_id' => $apply->user_id,
            'user_group_id' => XilujobUser::GROUP_MEMBER,
            'type' => PersonalMessageModel::TYPE_APPLY_REJECTED,
            'title' => '您投递的简历被拒绝',
            'content' => "您投递的\"{$job->job_name}\"已经被拒绝。",
            'extra' => ['job_id'=>$apply->job_id]
        ]);
        XilujobUser::where('user_id', $apply->user_id)->update(['personal_message'=>Db::raw('personal_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        //Notification::instance()->sendApplyRejected($apply);
    }

    /**
     * 面试邀请， 通知用户
     */
    public function xilujobInterviewSent(JobInterview &$interview) {
        // 发消息
        $job = Job::field('id,job_name')->where('id',$interview->job_id)->find();
        $enterpriseInfo = EnterpriseInfo::field('id,company_name')->where(['company_id'=>$interview->company_id])->find();
        $model = PersonalMessageModel::create([
            'user_id' => $interview->user_id,
            'user_group_id' => XilujobUser::GROUP_MEMBER,
            'type' => PersonalMessageModel::TYPE_INTERVIEW_SENT,
            'title' => '有公司邀请您面试',
            'content' => sprintf('"%s"邀请您面试职位"%s"',$enterpriseInfo->company_name, $job->job_name),
            'extra'=>['interview_id'=>$interview->id,'job_id'=>$interview->job_id,'company_id'=>$interview->company_id]
        ]);
        XilujobUser::where('user_id', $interview->user_id)->update(['personal_message'=>Db::raw('personal_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }

        try{
            Chat::add_chat([
                'message'=> ['type'=> "tags", 'content'=> ['text'=> "邀请面试",'interview_id'=>$interview->id]],
                'puser_id'=> $interview['user_id'],
                'type'=> "chat"
            ]);
        }catch (\Exception $e){

        }

//        if(isset($interview->send_message) && $interview->send_message==1) {
//            Notification::instance()->sendInterviewSent($interview);
//        }
    }

    /**
     * 面试邀请被拒， 通知企业
     */
    public function xilujobInterviewRejected(JobInterview &$interview) {
        // 发消息
        $job = Job::field('id,user_id,job_name')->where('id',$interview->job_id)->find();
        $model = PersonalMessageModel::create([
            'user_id' => $interview->user_id,
            'company_id' => $interview->company_id,
            'user_group_id' => XilujobUser::GROUP_COMPANY,
            'type' => PersonalMessageModel::TYPE_INTERVIEW_REJECTED,
            'title' => '您发出的面试邀请被拒绝',
            'content' => sprintf('您发出的面试邀请"%s"被拒绝',$job->job_name),
            'extra' => ['interview_id'=>$interview->id,'job_id'=>$interview->job_id,'user_id'=>$interview->user_id,'resume_id'=>$interview->resume_id]
        ]);
        XilujobUser::where('user_id', $job->user_id)->update(['discover_message'=>Db::raw('discover_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        //消息变成拒绝
        $chat = Chat::where('interview_id',$interview->id)->find();
        if($chat){
            $content = $chat['message_text'];
            $content['status'] = $interview->status;
            $chat->allowField(['message'])->save(['message'=>json_encode($content)]);
        }
        //Notification::instance()->sendInterviewRejected($interview);
    }

    //面试邀请被接受， 通知企业
    public function xilujobInterviewAccepted(JobInterview &$interview) {
        // 发消息
        $job = Job::field('id,user_id,job_name')->where('id',$interview->job_id)->find();
        $model = PersonalMessageModel::create([
            'user_id' => $interview->user_id,
            'company_id' => $interview->company_id,
            'user_group_id' => XilujobUser::GROUP_COMPANY,
            'type' => PersonalMessageModel::TYPE_INTERVIEW_ACCEPTED,
            'title' => '您发出的面试邀请已被接受',
            'content' => sprintf('您发出的面试邀请"%s"已被接受， 请在指定时间准备面试。', $job->job_name),
            'extra' => ['interview_id'=>$interview->id,'job_id'=>$interview->job_id,'user_id'=>$interview->user_id,'resume_id'=>$interview->resume_id]
        ]);
        XilujobUser::where('user_id', $job->user_id)->update(['discover_message'=>Db::raw('discover_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        //消息变成同意
        $chat = Chat::where('interview_id',$interview->id)->find();
        if($chat){
            $content = $chat['message_text'];
            $content['status'] = $interview->status;
            $chat->allowField(['message'])->save(['message'=>json_encode($content)]);
        }
        //Notification::instance()->sendInterviewAccepted($interview);
    }

    /**
     * 审核结果，提醒企业用户
     */
    public function xilujobAuditResult(&$companyProfile) {
        $content = $companyProfile->audit_status == 1 ? "您的企业已审核通过，可以进行发布岗位上架" : "您的企业认证未通过，".$companyProfile['refuse_reason'].'，请进行修改';
        $model = PersonalMessageModel::create([
            'user_id' => $companyProfile->user_id,
            'company_id' => $companyProfile->id,
            'user_group_id' => XilujobUser::GROUP_COMPANY,
            'type' => PersonalMessageModel::TYPE_COMPANY_CHECK,
            'title' => '企业审核结果',
            'content' => $content,
            'extra' => ['user_id'=>$companyProfile->user_id,'company_id'=>$companyProfile->id]
        ]);
        XilujobUser::where('user_id', $companyProfile->user_id)->update(['discover_message'=>Db::raw('discover_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        return true;
    }

    //面试失败， 通知用户
    public function xilujobInterviewFailed(JobInterview &$interview) {
        // 发消息
        $job = Job::withTrashed()->field('id,job_name')->where('id',$interview->job_id)->find();
        $enterpriseInfo = EnterpriseInfo::field('id,company_name')->where('company_id',$interview->company_id)->find();
        $model = PersonalMessageModel::create([
            'user_id' => $interview->user_id,
            'user_group_id' => XilujobUser::GROUP_MEMBER,
            'type' => PersonalMessageModel::TYPE_INTERVIEW_FAILED,
            'title' => '您的面试没有通过',
            'content' => sprintf('您在"%s"面试的职位"%s"没有通过，请再接再厉。', $enterpriseInfo->company_name, $job->job_name)
        ]);
        XilujobUser::where('user_id', $interview->user_id)->update(['personal_message'=>Db::raw('personal_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        //Notification::instance()->sendInterviewFailed($interview);
    }

    //面试通过， 通知用户
    public function xilujobInterviewPassed(JobInterview &$interview) {
        // 发消息
        $job = Job::field('id,job_name')->where('id',$interview->job_id)->find();
        $enterpriseInfo = EnterpriseInfo::field('id,company_name')->where('company_id',$interview->company_id)->find();
        $model = PersonalMessageModel::create([
            'user_id' => $interview->user_id,
            'user_group_id' => XilujobUser::GROUP_MEMBER,
            'type' => PersonalMessageModel::TYPE_INTERVIEW_PASSED,
            'title' => '您的面试已通过',
            'content' => sprintf('您在"%s"面试的职位"%s"已通过面试。', $enterpriseInfo->company_name, $job->job_name)
        ]);
        XilujobUser::where('user_id', $interview->user_id)->update(['personal_message'=>Db::raw('personal_message+1')]);
        if($model->getError()) {
            Log::error('消息发送失败:'.$model->getError());
        }
        //Notification::instance()->sendInterviewPassed($interview);
    }

    /**
     * 会员中心边栏后
     * @return mixed
     * @throws \Exception
     */
    public function userSidenavAfter()
    {
        $request = Request::instance();
        $actionname = strtolower($request->action());
        $data = [
            'actionname' => $actionname
        ];
        return $this->fetch('view/hook/user_sidenav_after', $data);
    }

}
